package org.jprogger.myworld.api.response.handler;


import java.util.ArrayList;
import java.util.List;

import org.jprogger.myworld.api.ApiServiceInvocationException;
import org.jprogger.myworld.api.app.ApiParams;
import org.jprogger.myworld.api.model.Audio;
import org.jprogger.myworld.api.request.ApiRequest;
import org.jprogger.myworld.api.response.ApiResponse;
import org.jprogger.myworld.api.response.ApiResponseData;
import org.jprogger.myworld.api.response.ApiResponseError;
import org.jprogger.myworld.api.response.AbstractApiResponseHandler;
import org.jprogger.myworld.api.response.DefaultApiResponse;
import org.jprogger.myworld.api.response.DefaultApiResponseData;
import org.jprogger.myworld.api.response.ParseResponseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetListAudioApiResponseHandler extends AbstractApiResponseHandler<List<Audio>> {

	@Override
	public ApiResponse<List<Audio>> handleResponse(ApiRequest request, String response) throws ApiServiceInvocationException {

		ApiResponseError apiError = null;
		ApiResponseData<List<Audio>> apiData = null;
		ApiResponse<List<Audio>> apiResponse = new DefaultApiResponse<List<Audio>>();
		String format = request.getRequestFormat();
		try 
		{
			apiError = validateResponse(response, format);
			if (apiError == null)
			{
				if (format.equals(ApiParams.JSON_REQUEST_FORMAT)) 
				{
					apiData = new DefaultApiResponseData<List<Audio>>();
					List<Audio> audios = new ArrayList<Audio>();
					
					JSONArray jsonAudios = new JSONArray(response);
					for (int i = 0; i < jsonAudios.length(); i++) 
					{
						Audio audio = new Audio();
						JSONObject jsonAudio = jsonAudios.getJSONObject(i);
						
						audio.setId(jsonAudio.getString("mid"));
						audio.setOwner(jsonAudio.getString("owner"));
						audio.setArtist(jsonAudio.getString("artist"));
						audio.setTitle(jsonAudio.getString("title"));
						audio.setDurationTime(jsonAudio.getLong("duration"));
						audio.setSize(jsonAudio.getLong("size"));
						audio.setCreatedTime(jsonAudio.getLong("created"));
						audio.setUrl(jsonAudio.getString("link"));
						audios.add(audio);
					}
					apiData.setData(audios);
				}
				else if (format.equals(ApiParams.XML_REQUEST_FORMAT))
				{
					// TODO: implement XML response format 
					throw new ApiServiceInvocationException("Unsupported response format");
				}
			}
			apiResponse.setError(apiError);
			apiResponse.setResponseData(apiData);
		} 
		catch (JSONException e)
		{
			throw new ApiServiceInvocationException("Bad response format", e);
		}
		catch (ParseResponseException e) 
		{
			throw new ApiServiceInvocationException("Unable to parse response", e);
		}
		return apiResponse;
	}
}
